<template>
  <view class="feedback-management">
    <!-- 页面头部 -->
    <view class="page-header">
      <uni-stat-breadcrumb class="breadcrumb" />
      <view class="header-content">
        <view class="page-title">
          <uni-icons type="chatboxes" size="24" color="#409EFF"></uni-icons>
          <text class="title-text">用户反馈管理</text>
        </view>
        <view class="header-stats">
          <view class="stat-item">
            <text class="stat-number">{{ statistics.total }}</text>
            <text class="stat-label">总反馈数</text>
          </view>
          <view class="stat-item">
            <text class="stat-number">{{ statistics.pending }}</text>
            <text class="stat-label">待处理</text>
          </view>
          <view class="stat-item">
            <text class="stat-number">{{ statistics.resolved }}</text>
            <text class="stat-label">已解决</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 搜索和筛选区域 -->
    <view class="search-section">
      <uni-card>
        <view class="search-form">
          <uni-easyinput 
            v-model="searchKeyword" 
            placeholder="搜索用户姓名、联系方式或反馈内容" 
            prefixIcon="search"
            clearable
            @confirm="handleSearch"
            @clear="handleSearch">
          </uni-easyinput>
          
          <uni-data-select 
            v-model="filterType" 
            :localdata="typeOptions" 
            placeholder="反馈类型"
            @change="handleSearch">
          </uni-data-select>
          
          <uni-data-select 
            v-model="filterStatus" 
            :localdata="statusOptions" 
            placeholder="处理状态"
            @change="handleSearch">
          </uni-data-select>
          
          <button class="search-btn" @click="handleSearch">
            <uni-icons type="search" size="16"></uni-icons>
            搜索
          </button>
          
          <button class="reset-btn" @click="resetSearch">
            <uni-icons type="refresh" size="16"></uni-icons>
            重置
          </button>
        </view>
      </uni-card>
    </view>

    <!-- 数据表格 -->
    <view class="table-section">
      <uni-card>
        <unicloud-db 
          ref="udb" 
          :collection="collectionList" 
          field="name,contact,type,description,images,createTime,createDate,status,adminReply,replyTime" 
          :where="where" 
          page-data="replace"
          :orderby="orderby" 
          :getcount="true" 
          :page-size="options.pageSize" 
          :page-current="options.pageCurrent"
          v-slot:default="{data,pagination,loading,error,options}" 
          :options="options" 
          loadtime="manual" 
          @load="onqueryload">
          
          <uni-table 
            ref="table" 
            :loading="loading" 
            :emptyText="error.message || '暂无反馈数据'" 
            border 
            stripe 
            type="selection" 
            @selection-change="selectionChange">
            
            <uni-tr>
              <uni-th align="center" width="80">序号</uni-th>
              <uni-th align="center" width="100" filter-type="search" @filter-change="filterChange($event, 'name')">用户姓名</uni-th>
              <uni-th align="center" width="120" filter-type="search" @filter-change="filterChange($event, 'contact')">联系方式</uni-th>
              <uni-th align="center" width="100" filter-type="select" :filter-data="options.filterData.type_localdata" @filter-change="filterChange($event, 'type')">反馈类型</uni-th>
              <uni-th align="center" width="200">反馈内容</uni-th>
              <uni-th align="center" width="100">处理状态</uni-th>
              <uni-th align="center" width="140" sortable @sort-change="sortChange($event, 'createTime')">提交时间</uni-th>
              <uni-th align="center" width="160">操作</uni-th>
            </uni-tr>
            
            <uni-tr v-for="(item,index) in data" :key="index">
              <uni-td align="center">{{ (options.pageCurrent - 1) * options.pageSize + index + 1 }}</uni-td>
              <uni-td align="center">
                <view class="user-info">
                  <uni-icons type="person" size="16" color="#909399"></uni-icons>
                  <text>{{ item.name }}</text>
                </view>
              </uni-td>
              <uni-td align="center">
                <view class="contact-info">
                  <text>{{ item.contact }}</text>
                </view>
              </uni-td>
              <uni-td align="center">
                <uni-tag :type="getTypeColor(item.type)" :text="item.type" size="small"></uni-tag>
              </uni-td>
              <uni-td align="center">
                <view class="content-preview" @click="showDetail(item)">
                  <text>{{ getContentPreview(item.description) }}</text>
                  <uni-icons v-if="item.images && item.images.length" type="image" size="14" color="#409EFF"></uni-icons>
                </view>
              </uni-td>
              <uni-td align="center">
                <uni-tag :type="getStatusColor(item.status)" :text="getStatusText(item.status)" size="small"></uni-tag>
              </uni-td>
              <uni-td align="center">
                <text class="time-text">{{ formatDateTime(item.createTime) }}</text>
              </uni-td>
              <uni-td align="center">
                <view class="action-buttons">
                  <button class="action-btn view-btn" @click="showDetail(item)">
                    <uni-icons type="eye" size="14"></uni-icons>
                    查看
                  </button>
                  <button class="action-btn reply-btn" @click="openReplyDialog(item)" v-if="item.status === 'pending'">
                    <uni-icons type="chat" size="14"></uni-icons>
                    回复
                  </button>
                  <button class="action-btn edit-btn" @click="navigateTo('./edit?id='+item._id+'&od='+encodeURIComponent(orderby)+'&field='+encodeURIComponent(JSON.stringify(filterData)))">
                    <uni-icons type="compose" size="14"></uni-icons>
                    编辑
                  </button>
                </view>
              </uni-td>
            </uni-tr>
          </uni-table>
          
          <view class="uni-pagination-box">
            <uni-pagination 
              show-icon 
              :page-size="pagination.size" 
              :current="pagination.current" 
              :total="pagination.count" 
              @change="onPageChanged" />
          </view>
        </unicloud-db>
      </uni-card>
    </view>

    <!-- 详情弹窗 -->
    <uni-popup ref="detailPopup" type="dialog">
      <uni-popup-dialog 
        mode="base" 
        title="反馈详情" 
        @close="closeDetail">
        <view class="detail-content" v-if="currentDetail">
          <view class="detail-section">
            <view class="detail-row">
              <text class="detail-label">用户信息</text>
            </view>
            <view class="detail-info-card">
              <view class="info-row">
                <uni-icons type="person" size="16" color="#409EFF"></uni-icons>
                <text>{{ currentDetail.name }}</text>
              </view>
              <view class="info-row">
                <uni-icons type="phone" size="16" color="#409EFF"></uni-icons>
                <text>{{ currentDetail.contact }}</text>
              </view>
              <view class="info-row">
                <uni-icons type="calendar" size="16" color="#409EFF"></uni-icons>
                <text>{{ formatDateTime(currentDetail.createTime) }}</text>
              </view>
            </view>
          </view>
          
          <view class="detail-section">
            <view class="detail-row">
              <text class="detail-label">反馈类型</text>
              <uni-tag :type="getTypeColor(currentDetail.type)" :text="currentDetail.type"></uni-tag>
            </view>
          </view>
          
          <view class="detail-section">
            <view class="detail-row">
              <text class="detail-label">反馈内容</text>
            </view>
            <view class="feedback-content">
              {{ currentDetail.description }}
            </view>
          </view>
          
          <view v-if="currentDetail.images && currentDetail.images.length" class="detail-section">
            <view class="detail-row">
              <text class="detail-label">相关图片</text>
            </view>
            <view class="images-grid">
              <image 
                v-for="(img, index) in currentDetail.images" 
                :key="index"
                :src="img" 
                class="detail-image"
                @click="previewImage(img, currentDetail.images)">
              </image>
            </view>
          </view>
          
          <view v-if="currentDetail.adminReply" class="detail-section">
            <view class="detail-row">
              <text class="detail-label">管理员回复</text>
            </view>
            <view class="admin-reply-content">
              <text>{{ currentDetail.adminReply }}</text>
              <text class="reply-time">{{ formatDateTime(currentDetail.replyTime) }}</text>
            </view>
          </view>
        </view>
      </uni-popup-dialog>
    </uni-popup>

    <!-- 回复弹窗 -->
    <uni-popup ref="replyPopup" type="dialog">
      <uni-popup-dialog 
        mode="input" 
        title="回复用户反馈" 
        placeholder="请输入回复内容..."
        v-model="replyContent"
        @confirm="submitReply"
        @close="closeReplyDialog">
      </uni-popup-dialog>
    </uni-popup>
  </view>
</template>
            <uni-td align="center">{{item.source}}</uni-td>
            <uni-td align="center">
                <text class="time-text">{{ formatDateTime(item.createTime) }}</text>
              </uni-td>
              <uni-td align="center">
                <view class="action-buttons">
                  <button class="action-btn view-btn" @click="showDetail(item)">
                    <uni-icons type="eye" size="14"></uni-icons>
                    查看
                  </button>
                  <button class="action-btn reply-btn" @click="openReplyDialog(item)" v-if="item.status === 'pending'">
                    <uni-icons type="chat" size="14"></uni-icons>
                    回复
                  </button>
                  <button class="action-btn edit-btn" @click="navigateTo('./edit?id='+item._id+'&od='+encodeURIComponent(orderby)+'&field='+encodeURIComponent(JSON.stringify(filterData)))">
                    <uni-icons type="compose" size="14"></uni-icons>
                    编辑
                  </button>
                </view>
              </uni-td>
            </uni-tr>
          </uni-table>
          
          <view class="uni-pagination-box">
            <uni-pagination 
              show-icon 
              :page-size="pagination.size" 
              :current="pagination.current" 
              :total="pagination.count" 
              @change="onPageChanged" />
          </view>
        </unicloud-db>
      </uni-card>
    </view>

    <!-- 详情弹窗 -->
    <uni-popup ref="detailPopup" type="dialog">
      <uni-popup-dialog 
        mode="base" 
        title="反馈详情" 
        @close="closeDetail">
        <view class="detail-content" v-if="currentDetail">
          <view class="detail-section">
            <view class="detail-row">
              <text class="detail-label">用户信息</text>
            </view>
            <view class="detail-info-card">
              <view class="info-row">
                <uni-icons type="person" size="16" color="#409EFF"></uni-icons>
                <text>{{ currentDetail.name }}</text>
              </view>
              <view class="info-row">
                <uni-icons type="phone" size="16" color="#409EFF"></uni-icons>
                <text>{{ currentDetail.contact }}</text>
              </view>
              <view class="info-row">
                <uni-icons type="calendar" size="16" color="#409EFF"></uni-icons>
                <text>{{ formatDateTime(currentDetail.createTime) }}</text>
              </view>
            </view>
          </view>
          
          <view class="detail-section">
            <view class="detail-row">
              <text class="detail-label">反馈类型</text>
              <uni-tag :type="getTypeColor(currentDetail.type)" :text="currentDetail.type"></uni-tag>
            </view>
          </view>
          
          <view class="detail-section">
            <view class="detail-row">
              <text class="detail-label">反馈内容</text>
            </view>
            <view class="feedback-content">
              {{ currentDetail.description }}
            </view>
          </view>
          
          <view v-if="currentDetail.images && currentDetail.images.length" class="detail-section">
            <view class="detail-row">
              <text class="detail-label">相关图片</text>
            </view>
            <view class="images-grid">
              <image 
                v-for="(img, index) in currentDetail.images" 
                :key="index"
                :src="img" 
                class="detail-image"
                @click="previewImage(img, currentDetail.images)">
              </image>
            </view>
          </view>
          
          <view v-if="currentDetail.adminReply" class="detail-section">
            <view class="detail-row">
              <text class="detail-label">管理员回复</text>
            </view>
            <view class="admin-reply-content">
              <text>{{ currentDetail.adminReply }}</text>
              <text class="reply-time">{{ formatDateTime(currentDetail.replyTime) }}</text>
            </view>
          </view>
        </view>
      </uni-popup-dialog>
    </uni-popup>

    <!-- 回复弹窗 -->
    <uni-popup ref="replyPopup" type="dialog">
      <uni-popup-dialog 
        mode="input" 
        title="回复用户反馈" 
        placeholder="请输入回复内容..."
        v-model="replyContent"
        @confirm="submitReply"
        @close="closeReplyDialog">
      </uni-popup-dialog>
    </uni-popup>
  </view>
</template>

<script>
  import { enumConverter, filterToWhere } from '../../js_sdk/validator/feedback.js';

  const db = uniCloud.database()
  // 表查询配置
  const dbOrderBy = '' // 排序字段
  const dbSearchFields = [] // 模糊搜索字段，支持模糊搜索的字段列表。联表查询格式: 主表字段名.副表字段名，例如用户表关联角色表 role.role_name
  // 分页配置
  const pageSize = 20
  const pageCurrent = 1

  const orderByMapping = {
    "ascending": "asc",
    "descending": "desc"
  }

  export default {
    data() {
      return {
        collectionList: "feedback",
        query: '',
        where: '',
        orderby: dbOrderBy,
        orderByFieldName: "",
        selectedIndexs: [],
        options: {
          pageSize,
          pageCurrent,
          filterData: {
            "type_localdata": [
              {
                "value": "功能建议",
                "text": "功能建议"
              },
              {
                "value": "问题反馈",
                "text": "问题反馈"
              },
              {
                "value": "使用体验",
                "text": "使用体验"
              },
              {
                "value": "其他",
                "text": "其他"
              }
            ],
            "status_localdata": [
              {
                "value": "pending",
                "text": "pending"
              },
              {
                "value": "processing",
                "text": "processing"
              },
              {
                "value": "resolved",
                "text": "resolved"
              },
              {
                "value": "closed",
                "text": "closed"
              }
            ],
            "priority_localdata": [
              {
                "value": "low",
                "text": "low"
              },
              {
                "value": "normal",
                "text": "normal"
              },
              {
                "value": "high",
                "text": "high"
              },
              {
                "value": "urgent",
                "text": "urgent"
              }
            ]
          },
          ...enumConverter
        },
        imageStyles: {
          width: 64,
          height: 64
        },
        exportExcel: {
          "filename": "feedback.xls",
          "type": "xls",
          "fields": {
            "用户姓名": "name",
            "联系方式": "contact",
            "反馈类型": "type",
            "详细描述": "description",
            "图片附件": "images",
            "客户端IP": "clientIP",
            "用户代理": "userAgent",
            "来源": "source",
            "创建时间戳": "createTime",
            "创建日期": "createDate",
            "处理状态": "status",
            "优先级": "priority",
            "管理员回复": "adminReply",
            "回复时间": "replyTime",
            "标签": "tags",
            "是否删除": "isDeleted",
            "版本号": "version"
          }
        },
        exportExcelData: []
      }
    },
    onLoad() {
      this._filter = {}
    },
    onReady() {
      this.$refs.udb.loadData()
    },
    methods: {
      onqueryload(data) {
        this.exportExcelData = data
      },
      getWhere() {
        const query = this.query.trim()
        if (!query) {
          return ''
        }
        const queryRe = new RegExp(query, 'i')
        return dbSearchFields.map(name => queryRe + '.test(' + name + ')').join(' || ')
      },
      search() {
        const newWhere = this.getWhere()
        this.where = newWhere
        this.$nextTick(() => {
          this.loadData()
        })
      },
      loadData(clear = true) {
        this.$refs.udb.loadData({
          clear
        })
      },
      onPageChanged(e) {
        this.selectedIndexs.length = 0
        this.$refs.table.clearSelection()
        this.$refs.udb.loadData({
          current: e.current
        })
      },
      navigateTo(url, clear) {
        // clear 表示刷新列表时是否清除页码，true 表示刷新并回到列表第 1 页，默认为 true
        uni.navigateTo({
          url,
          events: {
            refreshData: () => {
              this.loadData(clear)
            }
          }
        })
      },
      // 多选处理
      selectedItems() {
        var dataList = this.$refs.udb.dataList
        return this.selectedIndexs.map(i => dataList[i]._id)
      },
      // 批量删除
      delTable() {
        this.$refs.udb.remove(this.selectedItems(), {
          success:(res) => {
            this.$refs.table.clearSelection()
          }
        })
      },
      // 多选
      selectionChange(e) {
        this.selectedIndexs = e.detail.index
      },
      confirmDelete(id) {
        this.$refs.udb.remove(id, {
          success:(res) => {
            this.$refs.table.clearSelection()
          }
        })
      },
      sortChange(e, name) {
        this.orderByFieldName = name;
        if (e.order) {
          this.orderby = name + ' ' + orderByMapping[e.order]
        } else {
          this.orderby = ''
        }
        this.$refs.table.clearSelection()
        this.$nextTick(() => {
          this.$refs.udb.loadData()
        })
      },
      filterChange(e, name) {
        this._filter[name] = {
          type: e.filterType,
          value: e.filter
        }
        let newWhere = filterToWhere(this._filter, db.command)
        if (Object.keys(newWhere).length) {
          this.where = newWhere
        } else {
          this.where = ''
        }
        this.$nextTick(() => {
          this.$refs.udb.loadData()
        })
      }
    }
  }
</script>

<style>
</style>
